<template>
  <div class="car">
    <h2>购物车</h2>
    <table>
      <tr>
        <th>勾选</th>
        <th>课程名称</th>
        <th>课程价格</th>
        <th>数量</th>
        <th>价格</th>
      </tr>
      <tr v-for="(item, index) of bookItem" :key="index">
        <td>
          <input type="checkbox" v-model="item.isActive" />
        </td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>
          <button @click="minus(index)">-</button>
          {{ item.number }}
          <button @click="add(index)">+</button>
        </td>
        <td>{{ item.number * item.price }}</td>
      </tr>
      <tr>
        <td></td>
        <td colspan="2">已选：{{ isActiveBook}} / {{ allBookList }}</td>
        <td colspan="2">总价：{{ allPrice }}</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  name: "Car",
  props: {
    bookItem: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    // 选中项
    isActiveBook() {
      return this.bookItem.filter(item => item.isActive === true).length;
    },
    // 购物车中，所有添加的书目
    allBookList() {
      return this.bookItem.length;
    },
    // 选中项的总价
    allPrice() {
      let num = 0;
      this.bookItem.forEach(item => {
        if (item.isActive) {
          num += item.number * item.price;
        }
      });
      return num;
    }
  },
  methods: {
    /**
     * 点击按钮，增加数量
     * @param {* 当前项索引值} index
     * 遵循单向数据流原则，父组件中的数据最好在父组件中改
     */
    add(index) {
      this.$emit("add", index);
    },
    /**
     * 点击按钮，减少数量
     * @param {* 当前项索引} index
     */
    minus(index) {
      this.$emit("minus", index);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
